// 1. 迭代器接口（定义遍历方法）
interface Iterator<T> {
    boolean hasNext();
    T next();
}

// 2. 集合接口（定义创建迭代器的方法）
interface Aggregate<T> {
    Iterator<T> createIterator();
}

// 3. 具体集合类：书架
class BookShelf implements Aggregate<String> {
    private String[] books;
    private int size = 0;

    public BookShelf(int capacity) {
        books = new String[capacity];
    }

    public void addBook(String book) {
        if (size < books.length) {
            books[size++] = book;
        }
    }

    @Override
    public Iterator<String> createIterator() {
        return new BookShelfIterator();
    }

    // 4. 具体迭代器（内部类，封装遍历逻辑）
    private class BookShelfIterator implements Iterator<String> {
        private int index = 0;

        @Override
        public boolean hasNext() {
            return index < size;
        }

        @Override
        public String next() {
            return books[index++];
        }
    }
}

public class Main {
    public static void main(String[] args) {
        BookShelf shelf = new BookShelf(3);
        shelf.addBook("Design Patterns");
        shelf.addBook("Clean Code");
        shelf.addBook("Refactoring");

        Iterator<String> it = shelf.createIterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}
